package com.bsoft.gol.hcs.clinical.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.PrescriptionTypeRequest;
import com.bsoft.gol.hcs.clinical.bean.req.QueryDrugInformationRequest;
import com.bsoft.gol.hcs.clinical.bean.req.RecipeDrugstoreRequest;
import com.bsoft.gol.hcs.clinical.bean.response.DrugInformationTotalResponse;
import com.bsoft.gol.hcs.clinical.bean.vo.DrugstoreDepartmentVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DrugstoreInfo;
import com.bsoft.gol.hcs.clinical.dao.*;
import com.bsoft.gol.hcs.clinical.service.IElectronicMedicalService;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import com.bsoft.gol.hcs.common.service.impl.CommonService;
import com.bsoft.gol.hcs.enumcase.PlatformEnum;
import com.bsoft.gol.hcs.enumcase.PrescriptionTypeEnum;
import hcn.base.PrescriptionTypeConfig;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.ParamsOrgQo;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.service.IElectronicMedicalHisService;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import com.bsoft.gol.hcs.his.service.impl.MedicalSkillsHisService;
import opensource.jpinyin.PinyinHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.satisfaction.bean.vo.DictionaryVo;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Description: 电子病历服务实现
 * @Author: zhaorb
 * @Date: 2020/5/25 9:37
 **/
@Service
public class ElectronicMedicalService implements IElectronicMedicalService {
    private static Logger logger = LoggerFactory.getLogger(ElectronicMedicalService.class);

    @Autowired
    BaseTcmDiseasesDAO baseTcmDiseasesDAO;
    @Autowired
    BaseWmDiseasesDAO baseWmDiseasesDAO;
    @Autowired
    OdsVisitMedicalDAO odsVisitMedicalDAO;
    @Autowired
    OdsDiagnosisDAO odsDiagnosisDAO;
    @Autowired
    MedicationDecoctionDAO medicationDecoctionDAO;
    @Autowired
    OdsPrescriptionApplyDAO odsPrescriptionApplyDAO;
    @Autowired
    OdsPrescriptionApplyDrugDAO odsPrescriptionApplyDrugDAO;
    @Autowired
    BaseDrugDAO baseDrugDAO;
    @Autowired
    SysDictionaryDAO sysDictionaryDAO;
    @Autowired
    ConsultAskDAO consultAskDAO;
    @Autowired
    AppDoctorDAO appDoctorDAO;
    @Autowired
    AccountDAO accountDAO;
    @Autowired
    MedicationUseRateDAO medicationUseRateDAO;
    @Autowired
    OdsPrescriptionInfoDAO odsPrescriptionInfoDAO;
    @Autowired
    OdsPrescriptionDrugDAO odsPrescriptionDrugDAO;
    @Autowired
    MedicationTakeWayDAO medicationTakeWayDAO;
    @Autowired
    MedicalSkillsHisService medicalSkillsHisService;
    @Autowired
    PrescriptionTypeConfigDAO prescriptionTypeConfigDAO;
    @Autowired
    private IElectronicMedicalHisService electronicMedicalHisService;
    @Autowired
    IBaseParameterService baseParameterService;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private MedicalSkillsService medicalSkillsService;
    @Value("${project_source}")
    private String projectSource;

    @Override
    public BaseResponse<List<PrescriptionTypeConfig>> queryPrescriptionTypeList(PrescriptionTypeRequest request) {
        BaseResponse<List<PrescriptionTypeConfig>> result = new BaseResponse();
        try {
            List<PrescriptionTypeConfig> configs = prescriptionTypeConfigDAO.queryPrescriptionTypeConfig(request.getObjectId());
            result.setData(configs);
            result.setCode(ResultCode.SUCCESS);
            result.setMessage("查询成功");
        } catch (Exception e) {
            result.setCode(ResultCode.ERROR);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * 获取处方类型
     *
     * @param orgId
     * @return
     */
    @Deprecated
    public List<DictionaryVo> getPrescriptionTypeList(String pinyinCode, String orgId, Integer pageNo, Integer pageSize) {
        List<DictionaryVo> dictionaryVos = new ArrayList<>();
        PrescriptionTypeRequest request = new PrescriptionTypeRequest();
        request.setObjectId(orgId);
        BaseResponse<List<PrescriptionTypeConfig>> baseResponse = this.queryPrescriptionTypeList(request);
        List<PrescriptionTypeConfig> prescriptionTypeConfigs = baseResponse.getData();
        if (CommonUtils.isNotEmpty(prescriptionTypeConfigs)) {
            for (PrescriptionTypeConfig typeConfig : prescriptionTypeConfigs) {
                DictionaryVo dictionaryVo = new DictionaryVo();
                dictionaryVo.setDicCode(typeConfig.getPrescriptionType());
                if ("1" == typeConfig.getPrescriptionType()) {
                    dictionaryVo.setDicName(PrescriptionTypeEnum.WESRERN_MEDICINE.getContent());
                } else if ("2" == typeConfig.getPrescriptionType()) {
                    dictionaryVo.setDicName(PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getContent());
                } else if ("3" == typeConfig.getPrescriptionType()) {
                    dictionaryVo.setDicName(PrescriptionTypeEnum.CHINESE_MEDICINE.getContent());
                } else {
                    dictionaryVo.setDicName(PrescriptionTypeEnum.OTHER_MEDICINE.getContent());
                }
                //拼音码过滤
                if (CommonUtils.isNotEmpty(pinyinCode) && CommonUtils.isNotEmpty(dictionaryVo.getDicName())) {
                    String code = PinyinHelper.getShortPinyin(dictionaryVo.getDicName());
                    if (CommonUtils.isNotEmpty(code)) {
                        if (pinyinCode.toLowerCase().equals(code.toLowerCase()) || pinyinCode.equals(dictionaryVo.getDicName())) {
                            dictionaryVos.add(dictionaryVo);
                        }
                    }
                } else {
                    dictionaryVos.add(dictionaryVo);
                }
            }
        }

        //分页返回
        if (CommonUtils.isNotEmpty(dictionaryVos)) {
            Integer startPage = pageSize * pageNo - pageSize < 0 ? 0 : pageSize * pageNo - pageSize;
            Integer size = dictionaryVos.size();//记录数
            Integer endPage = pageNo * pageSize > size ? size : pageNo * pageSize;
            if (startPage.intValue() > size) {
                return null;
            }
            List<DictionaryVo> pageList = dictionaryVos.subList(startPage, endPage);
            return pageList;
        }

        return dictionaryVos;
    }

    /**
     * @description: 获取科室开方的药品类型所对应的药房代码
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/14 15:41
     * @param: request
     * @param: baseResponse
     * @return: java.lang.String
     */
    @Override
    public String getPharmacyCode(QueryDrugInformationRequest request, BaseResponse<DrugInformationTotalResponse> baseResponse) {
        DrugstoreInfo drugstoreInfo = getDrugstoreInfo(request);
        String pharmacyCode = "0";
        //1西药 2中成药 3中草药
        if (request.getDrugType().contains("1")) {
            pharmacyCode = String.valueOf(drugstoreInfo.getWesternMedicineDrugstore());
        } else if (request.getDrugType().contains("2")) {
            pharmacyCode = String.valueOf(drugstoreInfo.getChinesePatentMedicineDrugstore());
        } else if (request.getDrugType().contains("3")) {
            pharmacyCode = String.valueOf(drugstoreInfo.getHerbalMedicineDrugstore());
        }
        if (Integer.parseInt(pharmacyCode) < 0) {
            baseResponse.setMessage("未获取到药房信息");
        }
        return pharmacyCode;
    }

    /**
     * @description: 查询科室所对应药房
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/19 19:16
     * @param: request
     * @return: clinical.bean.vo.DrugstoreInfo
     */
    public DrugstoreInfo getDrugstoreInfo(QueryDrugInformationRequest request) {
        RecipeDrugstoreRequest recipeDrugstoreRequest = new RecipeDrugstoreRequest();
        DrugstoreDepartmentVo deptInfo = new DrugstoreDepartmentVo();
        deptInfo.setDeptId(request.getDeptId());
        deptInfo.setVisitOrganization(request.getHospitalCode());

        if (Constants.GOL.equals(projectSource)) {
            //根据健康通的orgId去查询健康通的机构信息，若是没有，代表当前的这个就是hospitalCode就是HIS那边的机构代码
            Map orgMap = getGOLOrgParamsByOrgId(request.getHospitalCode());
            if (null != orgMap) {
                deptInfo.setVisitOrganization((String) orgMap.get("organizationId"));
                request.setHospitalCode((String) orgMap.get("organizationId"));
            }
        }
        recipeDrugstoreRequest.setDepartment(deptInfo);

        //先从his获取药房代码再从处方平台获取药品信息
        //0 json  ; 1 xml
        String parameterValue = commonService.getParameterValue(request.getHospitalCode(), PlatformEnum.electronic_prescription);
        BaseResponse<DrugstoreInfo> resDrugstore;
        //去医院平台查，xml对接
        if ("1".equals(parameterValue)) {
            resDrugstore = electronicMedicalHisService.hisPlateformRecipeDrugstore(recipeDrugstoreRequest);
            //实时查his，json对接
        } else {
            resDrugstore = electronicMedicalHisService.recipeDrugstore(recipeDrugstoreRequest);
        }
        return resDrugstore.getData();
    }

    /**
     * @description: 查询健康通的机构列表信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/29 15:05
     */
    @Override
    public Map getGOLOrgParamsByOrgId(String orgId) {
        ParamsOrgQo qo = new ParamsOrgQo();
        qo.setOrgId(orgId);
        List<Map> maps = (List<Map>) baseDataService.queryOrganizationList(qo).getData();
        if (CommonUtils.isNotEmpty(maps)) {
            for (Map map : maps) {
                if (Constants.GOL.equals(projectSource)) {
                    return map;
                }
            }
        }
        return null;
    }

}
